package com.wp.动态规划;

/**
 * @author 王萍
 * @date 2018/4/6 0006
 * 动态规划
 * sum[i][j]代表在矩阵grid[i][j]处的最小和。
 * 转移方程为sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
 */
public class 最小路径和 {
    public static void main(String[] args) {
        int arr[][] = new int[][]{{1, 3, 9, 9}, {4, 9, 3, 4}, {1, 3, 2, 4}, {1, 1, 1, 0}};
        System.out.println(minPathSum(arr));
    }

    public static int minPathSum(int[][] grid) {
        int hang = grid.length;
        int lie = grid[0].length;
        int[][] sum = new int[hang][lie];
        sum[0][0] = grid[0][0];
        for (int i = 1; i < hang; i++) {
            sum[i][0] = sum[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < lie; i++) {
            sum[0][i] += sum[0][i - 1] + grid[0][i];
        }
        for (int i = 1; i < hang; i++) {
            for (int j = 1; j < lie; j++) {
                sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
            }
        }
        return sum[hang - 1][lie - 1];
    }
}
